package deliciouse.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import deliciouse.dao.MessagesDao;
import deliciouse.entity.Food;
import deliciouse.entity.Messages;

public class MessagesDaoImpl implements MessagesDao {
	private static class MessagesRowMapper implements RowMapper<Messages>{

		public Messages mapRow(ResultSet rs) throws SQLException {
			Messages messages = new Messages();
			messages.setId(rs.getInt("id"));
			messages.setUsername(rs.getString("username"));
			messages.setEmail(rs.getString("email"));
			messages.setContent(rs.getString("content"));
			messages.setPhone(rs.getString("phone"));
			messages.setPublishdate(rs.getDate("publishdate"));
			
			return messages;
		}
		
	}
	
	JdbcTemplate db = new JdbcTemplate();
	@Override
	public List<Messages> fetchByDate(int pageNum,int pageSize) {
		String sql ="select * from messages order by publishdate desc limit ?,?";
		
		return db.queryList(sql, new MessagesRowMapper(), (pageNum-1)*pageSize,pageSize);
	}
	@Override
	public boolean addMessage(Messages messages) {
		ArrayList parameters = new ArrayList();
		String sql = "insert into messages(username,phone,email,content,publishdate)values(?,?,?,?,?)";
		parameters.add(messages.getUsername());
		parameters.add(messages.getPhone());
		parameters.add(messages.getEmail());
		parameters.add(messages.getContent());
		parameters.add(messages.getPublishdate());
		 db.executeUpdate(sql, parameters.toArray());
		 return true;
	}
	@Override
	public int MessageMaxRows() {
		int rows =0;
		String sql ="select count(*) from messages";
		return rows= (int) db.query(sql, new RowMapper<Object>() {
			public Object mapRow(ResultSet rs) throws SQLException {
				return	rs.getInt(1);
			}
		});
	}


}
